package com.shi.yibanjia.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.shi.yibanjia.common.ResultCodeEnum;
import com.shi.yibanjia.common.UserContext;
import com.shi.yibanjia.common.exception.CustomException;
import com.shi.yibanjia.entity.po.User;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.shi.yibanjia.common.constant.RedisConstant.TOKEN_PREFIX;

/**
 * 用于用户请求的授权
 */
@Component
public class AuthCheckInterceptor implements HandlerInterceptor {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 获取token
        String token = request.getHeader("authorization");
        if (StrUtil.isBlank(token)) {
            throw new CustomException(ResultCodeEnum.NO_LOGIN);
        }
        // 2. 校验token
        String userJson=stringRedisTemplate.opsForValue().get(TOKEN_PREFIX + token);
        if (StrUtil.isBlank(userJson)){
            throw new CustomException(ResultCodeEnum.LOGIN_OVERDUE);
        }
        User user=JSONUtil.toBean(userJson, User.class);
        // 3. 放行
        UserContext.setUser(user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.remove();
    }
}
